<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\BookResource;
use App\Models\Book;
use Jiannei\Response\Laravel\Support\Facades\Response;

class BookController extends Controller
{
    public function index()
    {
        $categoryId = request('category_id');
        $books = Book::query()->scopes(['enable', 'sort'])
            ->when($categoryId, function ($query) use ($categoryId) {
                $query->where('category_id', $categoryId);
            })
            ->paginate(getPerPage());

        return Response::success(BookResource::collection($books));
    }

    public function show(Book $book)
    {
        return Response::success(new BookResource($book));
    }

    public function category()
    {
        $category = Book::$category;
        $data = [];
        foreach ($category as $k => $v) {
            $data[] = [
                'id' => $k,
                'name' => $v,
            ];
        }

        return Response::success(compact('data'));
    }

}
